/**  
 * @Title:  ValidationUtils.java   
 * @Package com.pay.app.util   
 * @author: chenao   
 * @date:   2018年8月23日 下午2:34:11   
 */
package com.chena.common.utils;
import java.util.Set;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.groups.Default;
import com.alibaba.fastjson.JSONObject;
import com.chena.common.exception.ServiceException;

/**
 * hibernate-validation校验工具类
 */
public class ValidationUtils {
	
	private static Validator validator = Validation.buildDefaultValidatorFactory().getValidator();

	public static <T> void validate(T obj) {
		Set<ConstraintViolation<T>> set = validator.validate(obj, Default.class);
		if (set.size() > 0) {
			throw new ServiceException(ServiceException.FAILED, String.format("参数:%s校验失败,%s", set.iterator().next().getPropertyPath().toString(), set.iterator().next().getMessage()));
		}
	}
	
	@SuppressWarnings("static-access")
	public static <T> void validateJsonObjStr(String paramsJsonStr, Class<T> clazz) {
		if(paramsJsonStr == null || paramsJsonStr.isEmpty()){
			throw new ServiceException(ServiceException.FAILED, "参数不能为空");
		}
		JSONObject jsonObject=JSONObject.parseObject(paramsJsonStr);
		T obj = jsonObject.toJavaObject(jsonObject, clazz);
		Set<ConstraintViolation<T>> set = validator.validate(obj, Default.class);
		if (set.size() > 0) {
			throw new ServiceException(ServiceException.FAILED, String.format("参数:%s校验失败,%s", set.iterator().next().getPropertyPath().toString(), set.iterator().next().getMessage()));
		}
	}

	public static void main(String[] args) {
//		CustomerRegisterDto c = new CustomerRegisterDto();
//		c.setUsername("fdsafsda");
//		ValidationUtils.validate(c);
	}
}
